package com.rambler.common.config;

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpRequestInterceptor;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author suhao
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        // 自动添加 Accept-Encoding:gzip
        HttpRequestInterceptor gzipInterceptor = (HttpRequest request, EntityDetails entityDetails,
                HttpContext context) -> {
            request.addHeader("Accept-Encoding", "gzip");
        };

        CloseableHttpClient httpClient = HttpClients.custom()
                .addRequestInterceptorLast(gzipInterceptor)
                .setDefaultHeaders(List.of(new BasicHeader("Accept-Encoding", "gzip")))
                .setConnectionManager(new PoolingHttpClientConnectionManager())
                .build();

        return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    }
}
